package by.wind.drebedengi.asynctask;

import by.wind.drebedengi.MainActivity;
import by.wind.drebedengi.R;
import by.wind.drebedengi.database.MyDatabaseHelper;
import by.wind.drebedengi.datalayer.GetRecordList;
import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;

public class UpgradeAsyncTask  extends AbstractTask{

	private Integer itsCurrentProgress;
	private final static int MAX = 10;
	
	public UpgradeAsyncTask(Context aContext) {
		super(aContext);
		itsProgressMessage = itsContext.getString(R.string.task_loading);
		itsCurrentProgress = 0;
	}
	
	@Override
	protected Boolean doInBackground(Long... params) {
		 // Check if task is cancelled
		try
        {
			GetRecordList recordList = new GetRecordList();
			MyDatabaseHelper helper = ((MainActivity)itsContext).getHelper();
			int count = 0;
			if (isCancelled()) return false;
			recordList.preLoadCurrencyData();
			publishProgress(++count);
			if (isCancelled()) return false;
			helper.updateCurrencyList(recordList.getCurrencyList());
			publishProgress(++count);
			if (isCancelled()) return false;
			recordList.preLoadCategoryData();
			publishProgress(++count);
			if (isCancelled()) return false;
			helper.updateCategoryList(recordList.getCategoryList());
			publishProgress(++count);
			if (isCancelled()) return false;
			recordList.preLoadPlaceData();
			publishProgress(++count);
			if (isCancelled()) return false;
			helper.updatePlaceList(recordList.getPlaceList());
			publishProgress(++count);
			if (isCancelled()) return false;
			recordList.preLoadSourceData();
			publishProgress(++count);
			if (isCancelled()) return false;
			helper.updateSourceList(recordList.getSourceList());
			publishProgress(++count);
			if (isCancelled()) return false;
			recordList.preLoadRecordData();
			publishProgress(++count);
			if (isCancelled()) return false;
			helper.updateRecordList(recordList.getRecordList());
			publishProgress(++count);
        }
        catch (Exception e)
        {
        	e.printStackTrace();
            Log.e("tag", e.getMessage());
            return false;
        }
        return true;
	}
	
	/* UI Thread */
	public void setProgressTracker(IProgressTracker progressTracker) {
		// Attach to progress tracker
		itsProgressTracker = progressTracker;
		// Initialize progress tracker with current task state
		if (itsProgressTracker != null) {
			itsProgressTracker.onProgress(itsProgressMessage,
					itsCurrentProgress, MAX);
			if (itsResult != null) {
				itsProgressTracker.onComplete();
			}
		}
	}
	
	protected void onProgressUpdate(Integer... values) {
		if (itsProgressTracker != null) {
			itsCurrentProgress = values[0];
			itsProgressTracker.onProgress(itsProgressMessage, values);
		}
			
	}

	@Override
	protected int getProgressType() {
		return ProgressDialog.STYLE_HORIZONTAL;
	}

	@Override
	public String onErrorMessage() {
		// TODO Auto-generated method stub
		return itsContext.getString(R.string.task_upgrade_error);
	}
	
	
}
